package com.xingdata.jjxc.activity;

import jar.MessageManager;
import jar.model.RequestEntity;
import jar.tools.InstructionSet;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.adapter.VlanListViewAdapter;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.utils.MessageCode;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.utils.WifiUtils;
import com.xingdata.jjxc.views.CustomDialog;

public class WlanListView extends Base1Activity {
	private String wifiPassword = null;
	private Button wifiSearchButton;
	private WifiUtils localWifiUtils;
	private ArrayList<ScanResult> wifiResultList = new ArrayList<ScanResult>();
	private List<String> wifiListString = new ArrayList<String>();
	private ListView wifiSearchListView;
	private VlanListViewAdapter adapter;
	private Handler mHandler;

	private void initWifiManager() {
		wifiListString.clear();
		localWifiUtils.WifiOpen();
		localWifiUtils.WifiStartScan();
		// 0正在关闭,1WIFi不可用,2正在打开,3可用,4状态不可zhi
		while (localWifiUtils.WifiCheckState() != WifiManager.WIFI_STATE_ENABLED) {// 等待Wifi开启
			Log.i("WifiState", String.valueOf(localWifiUtils.WifiCheckState()));
		}
		try {
			Thread.sleep(3000);// 休眠3s，不休眠则会在程序首次开启WIFI时候，处理getScanResults结果，wifiResultList.size()发生异常
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		wifiResultList.addAll((ArrayList<ScanResult>) localWifiUtils
				.getScanResults());
		localWifiUtils.getConfiguration();
		if (wifiListString != null) {
			Log.i("WIFIButtonListener", "dataChange");
			scanResultToString(wifiResultList, wifiListString);
		}
	}

	class ListOnItemClickListener implements OnItemClickListener {
		String SSID = null;

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1,
				final int postion, long arg3) {
			// TODO Auto-generated method stub
			Log.i("ListOnItemClickListener", "start");
			SSID = wifiResultList.get(postion).SSID;
			// 没有配置好信息，配置
			final CustomDialog.Builder builder = new CustomDialog.Builder(
					WlanListView.this, R.layout.dialog_wifi_config);
			builder.setTitle(wifiResultList.get(postion).SSID);
			builder.setPositiveButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

			builder.setNegativeButton("连接",
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							View view = builder.getDialogView();
							wifiPassword = ((EditText) view
									.findViewById(R.id.password)).getText()
									.toString().trim();
							if (wifiPassword.length() < 0) {
								showToast("密码不能为空");
								return;
							}
							
							
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("wifi_name", SSID);
							jsonObject.put("wifi_pwd", wifiPassword);
							jsonObject.put("flag", "1");
							MessageManager
									.send(Integer.parseInt(SystemInfo.getSendPORT()),
											new RequestEntity(
													jsonObject.toJSONString(),
													InstructionSet.INSTRUCTION_AUTH_HOTSPOT_TO_HUD
															+ ""));
							int wifiItemId = localWifiUtils.IsConfiguration(SSID);
							if (wifiItemId != -1) {
								// 连接过不需要密码直接连接
								if (localWifiUtils.ConnectWifi(wifiItemId)) {// 连接指定WIFI
									showToast("连接WIFI" + wifiResultList.get(postion).SSID
											+ "成功");
								}
							}else {
								int netId = localWifiUtils.AddWifiConfig(wifiResultList,SSID, wifiPassword);
								Log.i("WifiPswDialog",String.valueOf(netId));
								if(netId != -1){
									localWifiUtils.getConfiguration();//添加了配置信息，要重新得到配置信息
									if(localWifiUtils.ConnectWifi(netId)){
										showToast("连接WIFI"
												+ wifiResultList.get(postion).SSID
												+ "成功");
									}else {
										showToast("连接WIFI"
												+ wifiResultList.get(postion).SSID
												+ "失败");
									}
								} 
							}
							
							dialog.dismiss();
						}
					});

			builder.create().show();

		}
	}

	// ScanResult类型转为String
	public void scanResultToString(List<ScanResult> listScan,
			List<String> listStr) {
		for (int i = 0; i < listScan.size(); i++) {
			ScanResult strScan = listScan.get(i);
			String str = strScan.SSID + "--" + strScan.BSSID;
			boolean bool = listStr.add(str);
			if (bool) {

				// arrayWifiAdapter.notifyDataSetChanged();//数据更新,只能单个Item更新，不能够整体List更新
			} else {
				Log.i("scanResultToSting", "fail");
			}
			Log.i("scanResultToString", listStr.get(i));
		}
		Message message = new Message();
		message.what = MessageCode.MessageCode_RefreshControl;
		mHandler.sendMessage(message);
		// adapter.notifyDataSetChanged();
	}

	/*
	 * private BroadcastReceiver WifiBroadcastRec = new BroadcastReceiver(){
	 * 
	 * @Override public void onReceive(Context context, Intent intent) { // TODO
	 * Auto-generated method stub String wifiAction = intent.getAction();
	 * if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(wifiAction)){ int
	 * wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.
	 * WIFI_STATE_ENABLED); if(wifiState == WifiManager.WIFI_STATE_ENABLED){ try
	 * { Thread.sleep(3000);//休眠3s，不休眠则会在程序首次开启WIFI时候，处理getScanResults结果，
	 * wifiResultList.size()发生异常 } catch (InterruptedException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } wifiResultList =
	 * localWifiUtils.getScanResults(); localWifiUtils.getConfiguration();
	 * if(wifiListString != null){
	 * scanResultToString(wifiResultList,wifiListString); } } } } };
	 */

	@Override
	protected int getContentViewId() {
		return R.layout.wlan_listview;
	}

	@Override
	protected String getTitleText() {
		return "WIFI列表";
	}

	@Override
	protected void initViews() {
		wifiSearchListView = (ListView) findViewById(R.id.wifiListView);
		adapter = new VlanListViewAdapter(wifiResultList, this);
		// arrayWifiAdapter = new
		// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,wifiListString);
		wifiSearchListView.setAdapter(adapter);
		ListOnItemClickListener wifiListListener = new ListOnItemClickListener();
		wifiSearchListView.setOnItemClickListener(wifiListListener);
		localWifiUtils = new WifiUtils(WlanListView.this);
		mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case MessageCode.MessageCode_RefreshControl:
					adapter.notifyDataSetChanged();
					dismissProgressDialog();
					break;

				default:
					break;
				}
			};
		};
		new selectWifiThread().start();
		showProgressDialog("正在获取WIFI列表");
	}

	class selectWifiThread extends Thread {
		@Override
		public void run() {
			super.run();
			initWifiManager();
		}

	}
}
